package com.itcoon.cloud.framework.mybatis.typehandler;

import org.apache.logging.log4j.util.Strings;
import org.springframework.core.CollectionFactory;

import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;

public abstract class AbstractCollectionToSegmentsTypeHandler<T> extends AbstractToStringTypeHandler<Collection<T>> {

    private static final char SEPARATOR = ';';

    private final  Class<? extends Collection> collectionType;

    protected AbstractCollectionToSegmentsTypeHandler(Class<? extends Collection> collectionType) {
        this.collectionType = collectionType;
    }

    @Override
    String convertNonNull(Collection<T> ts) {
        return Strings.join(ts.stream().map(this::convertSingle).collect(Collectors.toList()), SEPARATOR);
    }

    @Override
    Collection<T> reverseNonNullConvert(String column) {
        String[] items = column.split(String.valueOf(SEPARATOR));
        return Arrays.stream(items).map(this::reverseConvertSingle).collect(Collectors.toCollection(()-> CollectionFactory.createCollection(collectionType, items.length * 2)));
    }

    public abstract String convertSingle(T t);

    public abstract T reverseConvertSingle(String item);
}
